#include<iostream>
#include<vector>
#include<cstring> 
#include<queue>
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 1e4 + 10, INF = 0x3f3f3f3f;

ll n, m;
vector<ll> g[N];
ll in[N], v[N];

void solve()
{
    while (cin >> n >> m) {
        memset(in, 0, sizeof in);
        memset(v, 0, sizeof v);
        for (int i = 1;i <= n;i++)
            g[i].clear();
        for (ll i = 1;i <= m;i++) {
            ll x, y;cin >> y >> x;
            g[x].push_back(y);
            in[y]++;
        }

        ll ans = 0, cnt = 0;
        queue<ll> q;
        for (ll i = 1;i <= n;i++) if (in[i] == 0) { q.push(i);v[i] = 888; }
        while (!q.empty()) {
            ll x = q.front();q.pop();
            cnt++;
            ans += v[x];
            for (ll y : g[x]) {
                in[y]--;
                v[y] = max(v[x], v[y]);
                if (in[y] == 0) { v[y]++;q.push(y); }
            }
        }
        if (cnt < n) cout << -1 << '\n';
        else cout << ans << '\n';
    }
}

signed main()
{
    //ios::sync_with_stdio(0);
    //cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    //cin>>T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}